//
//  UIColorExtension.swift
//  SwiftDemo1
//
//  Created by wzp on 2025/5/27.
//

import Foundation
import UIKit

extension UIColor {
    static func hexColor(_ hexValue: Int, alpha: Float) -> UIColor {
        let red = CGFloat((hexValue & 0xFF0000) >> 16)
        let green = CGFloat((hexValue & 0x00FF00) >> 8)
        let blue = CGFloat(hexValue & 0x0000FF)
        return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: CGFloat(red))
    }
    
    static func hexColor(_ hexValue: Int) -> UIColor {
        return UIColor.hexColor(hexValue, alpha: 1)
    }
    
    convenience init(_ hexValue: Int, alpha: Float) {
        let red = CGFloat((hexValue & 0xFF0000) >> 16)
        let green = CGFloat((hexValue & 0x00FF00) >> 8)
        let blue = CGFloat(hexValue & 0x0000FF)
        self.init(red: red / 255, green: green / 255, blue: blue / 255, alpha: CGFloat(red))
    }
    
    convenience init(_ hexValue: Int) {
        self.init(hexValue, alpha: 1)
    }
    
    func toImage() -> UIImage? {
        let rect = CGRectMake(0, 0, 5, 5);
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(self.cgColor)
        context?.fill([rect])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
